/**
 * Created by shenhai on 15/9/16.
 */


var authService = require('../../../services/mis/appuser/userAuthService');
var messageUtil = require('../../../common/utils/messageUtil');
var toolUtil = require('../../../common/utils/toolUtil');
var mysqlUtil = require('../../../common/utils/mysqlUtil');
var userInvitation = mongoose.model('user_invitation');
var backUserService = require('../../../services/backoffice/backOffice-userService');
var userDevice = mongoose.model('user_device_profile');
var inviteRecord = mongoose.model('invite_score_record');


exports.authList = function (req, res) {

    authService.authListService(req, function (err, results) {

        if (err) {
            logger.error('Exception happen when authList...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happen when authList...'));
        } else {
            var data = {
                count: results[1]["count"],
                totalPage: results[1]["totalPage"],
                list: results[2]
            };
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }

    });
};


exports.authenticate = function (req, res) {

    var body = req.body;

    authService.authenticateService(req, function (err, result) {
        if (err) {
            logger.error('Exception happened when authenticate ...' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when authenticate ...'));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, {}));

            if (body.status) {
                exports.authenticationAddScore(body.user);
            }
            //
            //    if (result[1] != null) {
            //
            //        mysqlUtil.generateUserVoucher(result[1], 2, body.user, function (err, voucher) {
            //            if (err) {
            //                logger.error(err.message);
            //            } else {
            //                userInvitation.update({invitee: body.user}, {
            //                    score: voucher.value,
            //                    dateLastModified: new Date(),
            //                    type: voucher.type
            //                }).exec();
            //
            //                //放入周排行榜
            //                var key = 'rank:invitation:' + moment().startOf('isoWeek').format('YYYYMMDD');
            //                redisClient.ZINCRBY(key, 1, result[1]);
            //
            //                //放入总排行榜
            //                var totalKey = 'rank:invitation:total';
            //                redisClient.ZINCRBY(totalKey, 1, result[1]);
            //            }
            //        });
            //
            //
            //        var message = {
            //            msgType: 'invite',
            //            userId: result[1],
            //            inviteUserId: body.user
            //        };
            //        toolUtil.putMessageBusinessMQ(message);
            //
            //        //建立相互关注
            //        backUserService.eachOtherFollowupService(body.user + '', result[1] + '');
            //    }
            //}
        }
    });
};

exports.refuseAuthenticate = function (req, res) {

    authService.refuseAuthenticateService(req, function (err, result) {
        if (err) {
            logger.error('Exception happened when refuseAuthenticate ...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when refuseAuthenticate ...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, {}));
        }
    })
};


exports.authenticationAddScore = function (token) {

    inviteRecord.findOne({
        user: token + '',
        source: 1
    }, function (err, invite) {
        if (invite != null) {
            logger.error('已有情值奖励，无法重复增加奖励')
        } else {
            var input = {
                userId: token + '',
                userRole: 1,
                addScore: V_SCORE,
                addScoreReason: 'V认证',
                userActionType: 1
            };

            input.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';

            scoreProxy.invoke('addScore', [input], function (err, result) {
                if (err) {
                    logger.error('Exception happened when addScoreManual ...!' + err.message);
                } else {
                    var data = JSON.parse(decodeURIComponent(result));
                    if (data.status == 0) {
                        var temp = new inviteRecord();
                        temp.user = token + '';
                        temp.source = 1;
                        temp.score = input.scoreAddCount;
                        temp.reason = input.scoreAddRason;
                        temp.save();

                    }
                }
            });
        }
    });


    //userDevice.findOne({userId: token}, 'vCode', function (err, version) {
    //    if ((version != null && version.vCode != null && version.vCode < 1403) || enbaleVoucher == 'No') {
    //        var arg = {
    //            userId: token,
    //            userRole: 1,
    //            userActionType: 1
    //        };
    //
    //        arg.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';
    //
    //        scoreProxy.invoke('addScore', [arg], function (err, reply) {
    //            try {
    //                var data = JSON.parse(decodeURIComponent(reply));
    //                if (err) {
    //                    logger.error('hessianInvokeAddScore-----' + err.message);
    //                } else if (data.status != 0) {
    //                    logger.error('hessianInvokeAddScore----' + data.status + '----' + data.msg);
    //                }
    //            } catch (e) {
    //                logger.error('hessianInvokeAddScore---' + e);
    //            }
    //        });
    //    } else {
    //        Users.findOne({_id: token}, function (err, user) {
    //            if (user == null || user.community == null) {
    //                logger.error('无效用户')
    //            } else {
    //                mysqlUtil.query('select * from voucher_user_bind where user_id=? and reward_source=1', [user._id + ''], function (err, result) {
    //                    if (err || result.length > 0) {
    //                        if (err)logger.error(err.message);
    //                        logger.error('v认证无法重复增加奖励')
    //                    } else {
    //
    //                        inviteRecord.findOne({
    //                            user: user._id + '',
    //                            source: 1
    //                        }, function (err, invite) {
    //                            if (invite != null) {
    //                                logger.error('已有情值奖励，无法重复增加奖励')
    //                            } else {
    //                                var community = user.community + '';
    //                                var nowDate = new Date().getTime();
    //                                var sql = 'select voucher_type_id,reward_expiredate_length,type,voucher_val,community_name from voucher_reward_rule r,voucher_type t where r.from_time<? and r.to_time>? and r.reward_source=? and r.community_id=? and t.id=r.voucher_type_id';
    //                                mysqlUtil.query(sql, [nowDate, nowDate, 1, community], function (err, result) {
    //                                    if (err || result.length == 0) {
    //                                        logger.error(err ? err : '无奖励规则');
    //                                    } else {
    //                                        if (result[0].type == 1) {
    //                                            mysqlUtil.getCardNumber(function (number) {
    //                                                var cardNo = moment().format('YYMMDD') + number;
    //                                                var expire = moment(nowDate).endOf('day').toDate().getTime() + result[0].reward_expiredate_length * 24 * 60 * 60 * 1000;
    //                                                var data = {
    //                                                    user_id: user._id + '',
    //                                                    expire_time: expire,
    //                                                    voucher_type_id: result[0].voucher_type_id,
    //                                                    is_use: 0,
    //                                                    reward_source: 1,
    //                                                    card_no: cardNo,
    //                                                    community_name: result[0].community_name,
    //                                                    create_time: new Date().getTime()
    //                                                };
    //                                                mysqlUtil.query('insert into voucher_user_bind set?', data, function (err, result) {
    //                                                    if (err) {
    //                                                        logger.error(err);
    //                                                    } else {
    //                                                        var content = {
    //                                                            type: 1,
    //                                                            flag: 2,
    //                                                            openType: 8,
    //                                                            contentId: user._id,
    //                                                            desc: '恭喜您！您获得了一张代金券'
    //                                                        };
    //                                                        var pushData = {
    //                                                            uList: [user._id],
    //                                                            content: content,
    //                                                            tag: '福利券',
    //                                                            type: 'operate'
    //                                                        };
    //                                                        toolUtil.putMessageGetuiPushMQ(pushData);
    //                                                    }
    //                                                })
    //                                            });
    //                                        } else if (result[0].type == 2) {
    //                                            var input = {
    //                                                userId: user._id + '',
    //                                                scoreAddCount: result[0].voucher_val,
    //                                                scoreAddRason: 'V认证'
    //                                            };
    //
    //                                            logger.info(input);
    //
    //                                            input.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';
    //
    //                                            scoreProxy.invoke('addScoreManual', [input], function (err, result) {
    //                                                if (err) {
    //                                                    logger.error('Exception happened when addScoreManual ...!' + err.message);
    //                                                    callback();
    //                                                } else {
    //                                                    var data = JSON.parse(decodeURIComponent(result));
    //                                                    logger.info(data);
    //                                                    if (data.status == 0) {
    //                                                        var temp = new inviteRecord();
    //                                                        temp.user = user._id + '';
    //                                                        temp.source = 1;
    //                                                        temp.score = input.scoreAddCount;
    //                                                        temp.reason = input.scoreAddRason;
    //                                                        temp.save();
    //
    //                                                    }
    //                                                }
    //                                            });
    //                                        }
    //                                    }
    //                                });
    //                            }
    //                        });
    //                    }
    //                });
    //            }
    //        })
    //    }
    //});
};